import csv
import os
import sys
import time
import tkinter as tk
from datetime import datetime
from tkinter import filedialog
from tkinter.messagebox import askyesno
from tkinter.scrolledtext import ScrolledText
import threading

import xlwt


class TestGui(object):
    def __init__(self, init_window_name):
        self.file_path = ""
        self.data_list_for_dic = []
        self.y_coordinate = []
        self.x_coordinate = []
        self.data_dict = {}
        self.sheet_name = "sheet"
        self.result_label = ""
        self.init_window_name = init_window_name
        self.init_window_name.title("CP921 by jc")  # 设置窗口标题
        self.init_window_name.geometry('700x350')  # 设置窗口大小
        """ 点击右上角关闭窗体弹窗事件 """
        self.init_window_name.protocol('WM_DELETE_WINDOW', lambda: self.thread_it(self.clos_window))
        """ 组件容器创建 """
        self.log_frame = tk.Frame(self.init_window_name)  # 创建存放日志组件的容器
        self.log_frame.grid(padx=20, pady=0, row=1, column=0, sticky=tk.W)
        self.runs_button_frame = tk.Frame(self.init_window_name)  # 创建存放日志组件的容器
        self.runs_button_frame.grid(padx=20, pady=0, row=2, column=0, sticky=tk.W)
        """ 日志框 """
        self.run_log = ScrolledText(self.log_frame, font=('楷体', 13), width=69, height=17)
        self.run_log.grid(padx=20, pady=5, row=0, column=0)
        """ 操作按钮 """
        self.open_button = tk.Button(self.runs_button_frame, text='打开文件', font=('行楷', 15, 'bold'), fg="white",
                                     bg="#1E90FF", width=25, command=self.ask_open_file)
        self.open_button.grid(padx=20, pady=0, row=0, column=1)
        self.write_button = tk.Button(self.runs_button_frame, text='开始转换', font=('行楷', 15, 'bold'), fg="white",
                                      bg="#1E90FF", width=25, command=lambda: self.thread_it(self.generate_excel))
        self.write_button.grid(padx=35, pady=0, row=0, column=2)

        # self.start_run1 = tk.Button(self.runs_button_frame, text='开始打印1', font=('行楷', 15, 'bold'), fg="white", bg="#1E90FF", width=25, command=lambda: self.thread_it(self.print1))
        # self.start_run1.grid(padx=20, pady=0, row=0, column=1)
        # self.start_run2 = tk.Button(self.runs_button_frame, text='开始打印2', font=('行楷', 15, 'bold'), fg="white",
        #                             bg="#1E90FF", width=25, command=lambda: self.thread_it(self.print2))
        # self.start_run2.grid(padx=35, pady=0, row=0, column=2)

    def thread_it(self, func, *args):
        """ 将函数打包进线程 """
        self.myThread = threading.Thread(target=func, args=args)
        self.myThread.setDaemon(True)  # 主线程退出就直接让子线程跟随退出,不论是否运行完成。
        self.myThread.start()

    def generate_excel(self):
        print("xls格式表格开始写入！")
        # 获取当前时间
        start_time = datetime.now()
        workbook = xlwt.Workbook()  # 新建一个工作簿
        # print(data_dict)
        sheet = workbook.add_sheet(self.sheet_name, cell_overwrite_ok=True)  # 新建一个工作表
        for i, x in enumerate(self.x_coordinate):
            # for i in range(100):
            #     tip_content = f'第{i}次打印 - 我是小汤1'
            #     self.run_log_print(message=tip_content)
            #     time.sleep(0.1)  # 睡眠
            # self.run_log_print(message='我是小汤1 - 打印完成')
            tip_content = f'xls格式表格正在写入{i + 1}/{len(self.x_coordinate)}'
            self.run_log_print(message=tip_content)
            self.init_window_name.update_idletasks()
            for y in self.y_coordinate:
                sheet.write(y, x, self.data_dict.get(str(x) + "+" + str(y), None))
        formatted_time = start_time.strftime("%Y%m%d-%H%M%S")
        print(formatted_time)
        out_directory = "D:/CP"
        if os.path.isdir(out_directory):
            print("目录存在")
        else:
            print("目录不存在,创建ing")
            os.makedirs(out_directory)
        out_all_path = f"D:/CP/huanxuan_CP921_out{formatted_time}.xls"
        workbook.save(out_all_path)  # 保存工作簿
        print("xls格式表格写入数据成功！")
        # 计算时间差
        end_time = datetime.now()
        time_difference = end_time - start_time
        print(f"总共耗时 {time_difference}")
        self.run_log_print(message=f'生成Excel成功,路径{out_all_path}')
        print(out_all_path)

    # def print1(self):
    # for i in range(100):
    #     tip_content = f'第{i}次打印 - 我是小汤1'
    #     self.run_log_print(message=tip_content)
    #     time.sleep(0.1)  # 睡眠
    # self.run_log_print(message='我是小汤1 - 打印完成')

    # def print2(self):
    #     for i in range(100, 200):
    #         tip_content = f'第{i}次打印 - 我是小汤2'
    #         self.run_log_print(message=tip_content)
    #         time.sleep(0.05)  # 睡眠
    #     self.run_log_print(message='我是小汤2 - 打印完成')

    def ask_open_file(self):
        self.file_path = filedialog.askopenfilename()
        print(self.file_path)
        tip_content = f'已选择文件:{self.file_path}'
        if self.file_path:
            print(self.file_path)
            with open(self.file_path, 'r') as file:
                reader = csv.reader(file)
                # start_index = 35
                # finish_index = 13686
                start_index = 27
                finish_index = 2504

                count = 0
                for i, row in enumerate(reader):
                    if i < start_index:
                        continue
                    if i > finish_index:
                        break
                    self.y_coordinate.append(int(row[7]))
                    self.x_coordinate.append(int(row[6]))
                    count += 1
                    # dataList.append(row[3] + row[4])
                    # dataList.append(row[2])
                    self.data_list_for_dic.append(row[4:8])
                for i in range(len(self.data_list_for_dic)):
                    self.data_dict[self.data_list_for_dic[i][2] + "+" + self.data_list_for_dic[i][3]] = \
                        self.data_list_for_dic[i][0]
        self.run_log_print(message=tip_content)

    def run_log_print(self, message):
        self.run_log.config(state=tk.NORMAL)
        self.run_log.insert(tk.END, "\n" + message + "\n")
        self.run_log.see(tk.END)
        self.run_log.update()
        self.run_log.config(state=tk.DISABLED)

    def clos_window(self):
        ans = askyesno(title='jc助手v1.1警告', message='是否确定退出程序？\n是则退出，否则继续！')
        if ans:
            self.init_window_name.destroy()
            sys.exit()
        else:
            return None


if __name__ == '__main__':
    """ 把button方法打包进线程，现实运行不卡顿 """
    """ 实例化出一个父窗口 """
    init_window = tk.Tk()
    """ tk界面置顶 """
    init_window.attributes("-topmost", 1)
    """ 创建Gui类对象 """
    test_gui = TestGui(init_window)
    """ 初始化GUi组件 """
    init_window.mainloop()
